package com.lovo.dao;


import java.sql.*;

/*
* DAO的父类，封装获取连接，关闭连接等操作
* */
public abstract class BaseDAO {
    protected Connection con;
    protected PreparedStatement statement;
    protected ResultSet rs;
    public Connection getConnection() {
        //加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //创建连接
//        Connection con = null;
        try {
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/atm?userSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT",
                    "root", "peng18383058225");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        System.out.println("con:" + con);
        return con;
    }

    public void close(Connection con, PreparedStatement statement) {
        if (statement != null) {
            try {
                statement.close();
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }


    }
    public  void close(Connection con,PreparedStatement statement,ResultSet resultSet) {
        if (statement != null) {
            try {
                resultSet.close();
                statement.close();
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }
    public  void close() {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (con!=null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


    public void setAutoCommit(boolean autoCommit){
        try {
            con.setAutoCommit(autoCommit);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public void commit(){
        try {
            con.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public void rollback(){
        try {
            con.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

}
